<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="700px" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="100px">
        <!-- 使用 el-row 和 el-col 实现一行两列布局 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排班日期" prop="scheduleDate">
              <el-date-picker style="width: 100%" clearable v-model="formData.scheduleDate" type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择排班日期"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班次" prop="shiftId">
              <el-select style="width: 100%" v-model="formData.shiftId" filterable clearable placeholder="请选择班次">
                <el-option v-for="item in shiftList" :key="item.id" :value="item.id" :label="item.shiftName">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产线" prop="deptId">
              <treeselect v-model="formData.deptId" :options="deptList" :flat="true" :normalizer="normalizer"
                          placeholder="产线" style="width: 100%;"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remarks">
              <el-input style="width: 100%" v-model="formData.remarks" placeholder="请输入备注"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import * as ScheduleApi from '@/api/lamp/schedule';
import * as ShiftApi from '@/api/lamp/shift';
import {listDept} from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "ScheduleForm",
  components: {
    Treeselect
  },
  data() {
    return {
      deptList: [],//产线列表

      shiftList: [],
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: {
        id: undefined,
        scheduleDate: undefined,
        shiftId: undefined,
        shiftName: undefined,
        remarks: undefined,
        deptId: undefined, // 添加deptId字段
      },
      // 表单校验
      formRules: {
        scheduleDate: [{required: true, message: '排班日期不能为空', trigger: 'blur'}],
        shiftId: [{required: true, message: '班次id不能为空', trigger: 'blur'}],
        deptId: [{required: true, message: '产线不能为空', trigger: 'blur'}], // 添加deptId必填校验
      },
    };
  },
  created() {
    this.getOptions()
  },
  methods: {
    normalizer(node) {
      // 构建基础对象，确保包含 id, label, children 属性
      const normalizedNode = {
        id: node.id,
        label: node.name,
        children: node.children, // 必须包含 children
      };

      // 关键：如果不是第三级节点，则禁用
      if (node.deptType !== 3) {
        normalizedNode.isDisabled = true; // 修改为 isDisabled
      } else {
      }
      console.log(normalizedNode);
      return normalizedNode;
    },
    // 递归函数为节点添加层级标记
    addLevelToNodes(nodes, currentLevel = 1) {
      if (!nodes || !Array.isArray(nodes)) {
        return [];
      }
      return nodes.map(node => {
        const newNode = {
          ...node,
          level: currentLevel
        };
        if (node.children && node.children.length > 0) {
          newNode.children = this.addLevelToNodes(node.children, currentLevel + 1);
        }
        return newNode;
      });
    },
    async getOptions() {
      listDept(this.queryParams).then(response => {
        this.deptList = this.addLevelToNodes(this.handleTree(response.data, "id"), 1);
        this.loading = false;
      })

      const res = await ShiftApi.getShiftPage({
        pageNo: 1,
        pageSize: 100
      });
      this.shiftList = res.data.list;
    },
    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;
      this.reset();
      // 修改时，设置数据
      if (id) {
        this.formLoading = true;
        try {
          const res = await ScheduleApi.getSchedule(id);
          this.formData = res.data;
          this.dialogTitle = "修改生产排班";
        } finally {
          this.formLoading = false;
        }
      } else {
        this.dialogTitle = "新增生产排班";
      }
    },
    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 修改的提交
        if (data.id) {
          await ScheduleApi.updateSchedule(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        await ScheduleApi.createSchedule(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        scheduleDate: undefined,
        shiftId: undefined,
        shiftName: undefined,
        remarks: undefined,
      };
      this.resetForm("formRef");
    }
  }
};
</script>
